package com.tomica.mailsigner;

import cfca.mobile.keydevice.AudioToken;

import com.Wsdl2Code.WebServices.SignService.VectorString;
import com.entersafe.safeca.Constant;
import com.entersafe.safeca.P11Other;
import com.tomica.mailsigner.R;
import com.tomica.mailsigner.fragment.PasswordDialogFragment;
import com.tomica.mailsigner.fragment.PasswordDialogFragment.PasswordDialogListener;
import com.tomica.mailsigner.fragment.SignMailFragment.SignEmailListener;
import com.tomica.mailsigner.fragment.SignPdfFragment.SignPdfListener;
import com.tomica.mailsigner.fragment.SignPdfFragment;
import com.tomica.mailsigner.signmail.SignMailModel;
import com.tomica.mailsigner.token.Token;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog.Builder;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MailSignerActivity extends FragmentActivity 
								implements ActionBar.TabListener,
											PasswordDialogListener,
											SignEmailListener,
											SignPdfListener{

	private static final String TAG = "MailSignerActivity";

	AppFragmentPageAdapter mFragmentAdapter;
	
	private BroadcastReceiver headSetReceiver = null;
	private Token token;
	private Uri uri;
	
	ViewPager mViewPager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mail_signer);
		
		// Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
		mFragmentAdapter = new AppFragmentPageAdapter(this,getSupportFragmentManager());
		
		final ActionBar actionBar = getActionBar();
		
		// Specify that tabs should be displayed in the action bar.
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    
	    // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
	    mViewPager = (ViewPager) findViewById(R.id.pager);
	    mViewPager.setAdapter(mFragmentAdapter);
	    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mFragmentAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mFragmentAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
        
        P11Other.audioToken = new AudioToken(this);
        
        // FIXME null?
        token = new Token(this, null);
     // Register listening to audiopass
     		headSetReceiver = new BroadcastReceiver() {
     			public void onReceive(Context context, Intent intent) {
     				String action = intent.getAction();
     				if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
     					// headphone plugged
     					if (intent.getIntExtra("state", 0) == 1) {
     						Log.i("Handset", "Handset plugin");
     						token.tryConnect();

     						// headphone unplugged
     					} else {
     						Log.i("Handset", "Handset plugout");
     						token.disConnect();
     						// TODO: show dialog to insert AudioPass showDialog(0);

     					}
     				}
     			}
     		};
     		registerReceiver(headSetReceiver, new IntentFilter(
     				Intent.ACTION_HEADSET_PLUG));
        
     		
     		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mail_signer, menu);
		return true;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(Constant.Debug, "onDestroy Email sign screen");
		// disConnect();
		P11Other.audioToken.Release();
		unregisterReceiver(headSetReceiver);
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction arg1) {
		
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction arg1) {
		// When the given tab is selected, switch to the corresponding page in the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
		
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		
		
	}
	
	private void showEditDialog() {
        FragmentManager fm = getSupportFragmentManager();
        PasswordDialogFragment passwordDialog = new PasswordDialogFragment();
        passwordDialog.show(fm, "fragment_dialog_password");
    }

	@Override
	public void onFinishEditDialog(String inputText) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSignMail(VectorString addressFrom, VectorString addressCc,
			String subject, String content) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCallSettings() {
		mViewPager.setCurrentItem(2);
		
	}
	
	public void checkFileIntent(){
		uri = getIntent().getData();
        
        if (uri == null){
        	Log.v(TAG,"No file");
        } else {
        	String fileName = uri.getLastPathSegment();
    		Log.v(TAG,"Uri-"+uri.toString()+" name ="+fileName);
    		mViewPager.setCurrentItem(1);
        }
	}
	
	@Override
	public void onResume(){
		super.onResume();
		checkFileIntent();	
	}

	@Override
	public Uri getPdfUri() {
		
		return uri;
	}
	
	
}
